<template>
	<view class="version-container">
		
		<!-- 版本创建表单 -->
		<view class="form-section">
			<text class="form-title">版本创建</text>
			
			<view class="form-item">
				<text class="label">
					请输入版本号
				</text>
				<input 
					v-model="formData.version" 
					:placeholder="`当前版本号: ${currentVersion}`"
					class="input" 
					@input="validateVersion"
				/>
				<text v-if="versionError" class="error-text">{{ versionError }}</text>
			</view>
			
			<view class="form-item">
				<text class="label">版本状态</text>
				<radio-group :value="formData.status" @change="onStatusChange" class="radio-group">
					<label class="radio-item">
						<radio value="1" color="#007aff" />
						<text class="radio-text">正常</text>
					</label>
					<label class="radio-item">
						<radio value="2" color="#007aff" />
						<text class="radio-text">维护</text>
					</label>
				</radio-group>
			</view>
			
			<view class="form-item">
				<text class="label">更新日志</text>
				<textarea 
					v-model="formData.version_desc" 
					placeholder="请输入版本更新内容" 
					class="textarea"
					auto-height
				></textarea>
			</view>
			
			<view class="form-item">
				<text class="label">下载地址</text>
				<input 
					v-model="formData.download_url" 
					placeholder="请输入版本下载URL" 
					class="input"
				/>
			</view>
			
			<button 
				:disabled="isCreating" 
				@click="createVersion" 
				class="submit-btn"
			>
				{{ isCreating ? '创建中...' : '创建版本' }}
			</button>
		</view>
		
		<!-- 最新版本信息 -->
		<view class="latest-version-section">
			<text class="section-title">最新版本信息</text>
			
			<view v-if="latestVersion">
				<!-- 需要更新显示版本卡片 -->
				<view v-if="compareVersions(currentVersion, latestVersion.version) < 0" class="version-card">
					<view class="version-info-item">
						<text class="info-label">版本号:</text>
						<text class="info-value">{{ latestVersion.version }}</text>
					</view>
					<view class="version-info-item">
						<text class="info-label">发布时间:</text>
						<text class="info-value">{{ latestVersion.create_time }}</text>
					</view>
					<view class="version-info-item">
						<text class="info-label">版本状态:</text>
						<text class="info-value status-{{ latestVersion.status }}">
							{{ latestVersion.status === 1 ? '正常' : '维护' }}
						</text>
					</view>
					<view class="version-info-item version-desc">
						<text class="info-label">更新日志:</text>
						<text class="info-value">{{ latestVersion.version_desc || '无' }}</text>
					</view>
					
					<button 
						@click="startDownload" 
						class="download-btn"
					>
						下载最新版本
					</button>
				</view>
				
				<!-- 版本相同庆祝提示 -->
				<view v-else-if="compareVersions(currentVersion, latestVersion.version) === 0" class="celebration-box">
					<text class="celebration-title">🎉 恭喜！</text>
					<text class="celebration-message">您当前使用的是最新版本</text>
				</view>
			</view>
			
			<!-- 暂无版本信息 -->
			<view v-else class="empty-data">
				<text class="empty-text">暂无版本信息</text>
			</view>
		</view>
		
		<!-- 下载进度弹窗 -->
		<view v-if="showDownloadProgress" class="download-popup">
			<view class="popup-content">
				<text class="popup-title">最新资源加载中</text>
				<view class="progress-container">
					<progress 
						:percent="downloadProgress" 
						stroke-width="8" 
						color="#007aff" 
						backgroundColor="#e8e8e8"
					/>
					<text class="progress-text">{{ downloadProgress }}%</text>
				</view>
				<text v-if="downloadError" class="download-error">{{ downloadError }}</text>
				<button 
					v-if="downloadError" 
					@click="cancelDownload" 
					class="close-btn"
				>
					关闭
				</button>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted, reactive, onUnmounted } from 'vue'
import { createVersion as apiCreateVersion, getLatestVersion as apiGetLatestVersion } from '@/static/apis/wzry.js'
import { getVersion } from '@/static/js/hub';
// 表单数据
const formData = reactive({
	version: '',
	status: '1',
	version_desc: '',
	download_url: ''
})
// 当前版本
const thiscurrentVersion = ref('0.0.0')

// 页面卸载时移除事件监听并保存下载进度
onUnmounted(() => {
	// 移除事件监听
	uni.offAppShow(onAppShow)
	uni.offAppHide(onAppHide)
	uni.offNetworkStatusChange(onNetworkStatusChange)
	
	// 如果正在下载，保存进度并终止下载
	if (isDownloading.value && downloadTask.value) {
		uni.setStorageSync('downloadProgress', downloadProgress.value)
		uni.setStorageSync('isDownloading', true)
		if (latestVersion.value && latestVersion.value.download_url) {
			uni.setStorageSync('downloadUrl', latestVersion.value.download_url)
		}
		uni.setStorageSync('downloadTaskId', downloadTaskId.value)
		
		// 终止下载任务
		downloadTask.value.abort()
		downloadTask.value = null
		isDownloading.value = false
	}
})

// 版本验证错误信息
const versionError = ref('')
// 创建状态
const isCreating = ref(false)
// 最新版本信息
const latestVersion = ref(null)
// 当前系统版本
const currentVersion = ref('0.0.0')
// 下载进度
const downloadProgress = ref(0)
// 下载错误信息
const downloadError = ref('')
// 是否显示下载进度
const showDownloadProgress = ref(false)
// 下载任务对象
const downloadTask = ref(null)
// 下载任务ID
const downloadTaskId = ref('')
// 下载状态
const isDownloading = ref(false)

// 页面加载时获取最新版本
onMounted(async () => {
	// 获取当前系统版本
	try {
		const res = await uni.getSystemInfo()
		currentVersion.value = res.appVersion
		
	} catch (e) {
		console.error('获取当前版本失败:', e)
		currentVersion.value = '0.0.0'
	}
	fetchLatestVersion()

	// 添加应用前后台切换事件监听
	uni.onAppShow(onAppShow)
	uni.onAppHide(onAppHide)
	// 添加网络状态变化事件监听
	uni.onNetworkStatusChange(onNetworkStatusChange)
})

// 验证版本号格式
const validateVersion = () => {
	const versionPattern = /^\d+\.\d+\.\d+$/;
	if (!versionPattern.test(formData.version)) {
		versionError.value = '版本号格式错误，必须为x.y.z形式'
	} else {
		versionError.value = ''
	}
}

// 创建版本
const createVersion = () => {
	// 表单验证
	if (!formData.version) {
		versionError.value = '请输入版本号'
		return
	}
	if (versionError.value) {
		return
	}
	if (!formData.download_url) {
		uni.showToast({
			title: '请输入下载地址',
			icon: 'error'
		})
		return
	}
	
	isCreating.value = true
	
	apiCreateVersion({
		version: formData.version,
		status: parseInt(formData.status),
		version_desc: formData.version_desc,
		download_url: formData.download_url
	}).then((res) => {
		if (res.code === 0) {
			uni.showToast({
				title: '版本创建成功',
				icon: 'success'
			})
			// 重置表单
			formData.version = ''
			formData.status = '1'
			formData.version_desc = ''
			formData.download_url = ''
			// 更新最新版本信息http://bd862459.natappfree.cc/midea/APPVersionList/1.2.2.apk
			fetchLatestVersion()
		}
	}).catch(err => {
		uni.showToast({
			title: err.message,
			icon: 'none'
		})
	})
	.finally(() => {
		isCreating.value = false
	})
}

// 获取最新版本信息
const fetchLatestVersion = () => {
	apiGetLatestVersion().then((res) => {
		if (res.code === 0) {
			latestVersion.value = res.data
		}
	})
}

// 版本比较函数
function compareVersions(v1, v2) {
	// 处理v1或v2为null的情况
	if (!v1 || !v2) return 0
	
	// 清除版本号前缀的非数字字符（如"v"、"version"）
	const cleanV1 = v1.replace(/^[^\d]+/, '')
	const cleanV2 = v2.replace(/^[^\d]+/, '')
	
	// 按点分割并转换为数字数组
	const v1Parts = cleanV1.split('.').map(Number)
	const v2Parts = cleanV2.split('.').map(Number)
	
	// 填充数组长度，确保比较的版本号部分数量一致
	const maxLength = Math.max(v1Parts.length, v2Parts.length)
	for (let i = 0; i < maxLength; i++) {
		const num1 = v1Parts[i] || 0
		const num2 = v2Parts[i] || 0
		
		if (num1 < num2) return -1 // v1 旧于 v2
		if (num1 > num2) return 1   // v1 新于 v2
	}
	
	return 0 // 版本号相同
}

// 开始下载
const startDownload = () => {
	if (!latestVersion.value || !latestVersion.value.download_url) {
		uni.showToast({
			title: '下载地址不存在',
			icon: 'error'
		})
		return
	}
	
	showDownloadProgress.value = true
	downloadProgress.value = 0
	downloadError.value = ''
	isDownloading.value = true
	
	// 开始下载
	const task = uni.downloadFile({
		url: latestVersion.value.download_url,
		success: (res) => {
			if (res.statusCode === 200 && res.tempFilePath) {
				// 下载完成，自动安装
				installAPK(res.tempFilePath)
				showDownloadProgress.value = false
				isDownloading.value = false
			} else {
				downloadError.value = `下载失败: ${res.statusCode || '无文件路径'}`
				isDownloading.value = false
			}
		},
		fail: () => {
			downloadError.value = '网络错误或文件不存在'
			isDownloading.value = false
		},
		complete: () => {
			if (downloadError.value) {
				// 下载失败时保持弹窗显示，直到用户关闭
			} else {
				showDownloadProgress.value = false
			}
		}
	})
	
	// 监听下载进度
	task.onProgressUpdate((progress) => {
		downloadProgress.value = progress.progress
	})
	
	// 保存下载任务信息
	downloadTask.value = task
	downloadTaskId.value = task.taskId
	
	// 保存初始下载信息到本地
	uni.setStorageSync('downloadProgress', 0)
	uni.setStorageSync('isDownloading', true)
	uni.setStorageSync('downloadUrl', latestVersion.value.download_url)
	uni.setStorageSync('downloadTaskId', task.taskId)
}

// 取消下载
const cancelDownload = () => {
	showDownloadProgress.value = false
	downloadError.value = ''
	isDownloading.value = false
	
	// 终止下载任务
	if (downloadTask.value) {
		downloadTask.value.abort()
		downloadTask.value = null
	}
	
	downloadTaskId.value = ''
	
	// 清除本地存储的下载信息
	uni.removeStorageSync('downloadProgress')
	uni.removeStorageSync('isDownloading')
	uni.removeStorageSync('downloadUrl')
	uni.removeStorageSync('downloadTaskId')
}

// 处理版本状态变化
const onStatusChange = (e) => {
	formData.status = e.detail.value
}

// 应用切换到前台
const onAppShow = () => {
	if (isDownloading.value && !downloadTask.value) {
		// 如果下载状态为true但下载任务对象不存在，则恢复下载
		resumeDownload()
	}
}

// 应用切换到后台
const onAppHide = () => {
	if (downloadTask.value) {
		// 保存当前下载进度
		uni.setStorageSync('downloadProgress', downloadProgress.value)
		uni.setStorageSync('isDownloading', true)
		// 仅在latestVersion和download_url存在时保存
		if (latestVersion.value && latestVersion.value.download_url) {
			uni.setStorageSync('downloadUrl', latestVersion.value.download_url)
		}
		uni.setStorageSync('downloadTaskId', downloadTaskId.value)
	}
}

// 网络状态变化
const onNetworkStatusChange = (res) => {
	if (!res.isConnected && downloadTask.value) {
		// 网络断开，保存下载进度
		uni.setStorageSync('downloadProgress', downloadProgress.value)
		uni.setStorageSync('isDownloading', true)
		uni.setStorageSync('downloadUrl', latestVersion.value.download_url)
		uni.setStorageSync('downloadTaskId', downloadTaskId.value)
		// 停止当前下载
		if (downloadTask.value) {
			downloadTask.value.abort()
			downloadTask.value = null
		}
		isDownloading.value = false
		uni.showToast({
			title: '网络已断开，下载暂停',
			icon: 'warn'
		})
	} else if (res.isConnected && isDownloading.value && !downloadTask.value) {
		// 网络恢复且有未完成的下载，恢复下载
		resumeDownload()
	}
}

// 恢复下载
const resumeDownload = () => {
	// 从本地存储获取下载信息
	const savedProgress = uni.getStorageSync('downloadProgress')
	const savedUrl = uni.getStorageSync('downloadUrl')
	const savedIsDownloading = uni.getStorageSync('isDownloading')
	
	// 检查是否有可恢复的下载任务
	const hasValidUrl = savedUrl || (latestVersion.value && latestVersion.value.download_url)
	if (!savedIsDownloading || !hasValidUrl || savedProgress >= 100) {
		// 无下载任务可恢复
		return
	}
	
	// 确定下载URL
	const downloadUrl = savedUrl || latestVersion.value.download_url
	
	showDownloadProgress.value = true
	downloadProgress.value = savedProgress
	downloadError.value = ''
	isDownloading.value = true
	
	// 开始恢复下载
	const task = uni.downloadFile({
		url: downloadUrl,
		header: {
			Range: `bytes=${savedProgress}-` // 请求从当前进度开始继续下载
		},
		success: (res) => {
			if ((res.statusCode === 206 || res.statusCode === 200) && res.tempFilePath) {
				// 下载完成，自动安装
				installAPK(res.tempFilePath)
				showDownloadProgress.value = false
				isDownloading.value = false
				// 清除本地存储的下载信息
				uni.removeStorageSync('downloadProgress')
				uni.removeStorageSync('isDownloading')
				uni.removeStorageSync('downloadUrl')
				uni.removeStorageSync('downloadTaskId')
			} else {
				downloadError.value = `下载失败: ${res.statusCode || '无文件路径'}`
				isDownloading.value = false
			}
		},
		fail: () => {
			downloadError.value = '网络错误或文件不存在'
			isDownloading.value = false
		},
		complete: () => {
			if (downloadError.value) {
				// 下载失败时保持弹窗显示，直到用户关闭
			} else {
				showDownloadProgress.value = false
			}
		}
	})
	
	// 监听下载进度
	task.onProgressUpdate((progress) => {
		// 计算实际总进度
		const actualProgress = savedProgress + (progress.progress * (100 - savedProgress) / 100)
		downloadProgress.value = actualProgress
	})
	
	// 保存下载任务信息
	downloadTask.value = task
	downloadTaskId.value = task.taskId
}

// 安装APK
const installAPK = (filePath) => {
	// 检查是否在APP环境中运行
	if (typeof plus !== 'undefined') {
		try {
			if (!filePath) {
				uni.showToast({
					title: '安装失败：无文件路径',
					icon: 'error'
				})
				return
			}
			
			// 转换文件路径（兼容不同平台）
			const localFilePath = plus.io.convertLocalFileSystemURL(filePath)
			
			// 调用系统安装（自动处理权限请求）
			plus.runtime.install(localFilePath, {
				force: true // 强制安装（覆盖旧版本）
			}, (success) => {
				uni.showToast({
					title: '安装成功，即将重启应用',
					icon: 'success'
				})
				// 安装完成后重启应用
				setTimeout(() => {
					plus.runtime.restart()
				}, 2000)
			}, (error) => {
				console.error('安装失败原因:', error)
				console.error('文件路径:', localFilePath)
				// 处理不同错误情况
				let errorMsg = '安装失败'
				if (error.message.includes('permission')) {
					errorMsg = '请开启未知应用安装权限'
					// 引导用户打开设置
					setTimeout(() => {
						plus.runtime.openURL('app-settings://')
					}, 1500)
				} else if (error.message.includes('parse')) {
					errorMsg = '安装包损坏或格式错误'
				} else if (error.message.includes('certificate')) {
					errorMsg = '安装包证书验证失败'
				} else if (error.message.includes('file not found')) {
					errorMsg = '安装包不存在'
				}
				uni.showToast({
					title: errorMsg,
					icon: 'error'
				})
			})
		} catch (e) {
			console.error('安装异常:', e)
			uni.showToast({
				title: '安装异常，请重试',
				icon: 'error'
			})
		}
	} else {
		uni.showToast({
			title: '安装功能仅支持APP端',
			icon: 'error'
		})
	}
}
</script>

<style scoped lang="scss">
.version-container {
	padding: 20rpx;
	background-color: #f5f5f5;
	min-height: 100vh;
}

.form-section {
	background-color: #fff;
	padding: 24rpx;
	border-radius: 12rpx;
	margin-bottom: 24rpx;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
}

.form-title {
	display: block;
	font-size: 32rpx;
	font-weight: 600;
	color: #333;
	margin-bottom: 24rpx;
}

.form-item {
	margin-bottom: 28rpx;
}

.label {
	display: block;
	font-size: 28rpx;
	color: #333;
	margin-bottom: 12rpx;
}

.input {
	width: 100%;
	height: 80rpx;
	padding: 0 20rpx;
	border: 2rpx solid #e8e8e8;
	border-radius: 8rpx;
	font-size: 28rpx;
	box-sizing: border-box;
	background-color: #fafafa;
	
	&:focus {
		border-color: #007aff;
		background-color: #fff;
	}
}

.textarea {
	width: 100%;
	min-height: 120rpx;
	padding: 20rpx;
	border: 2rpx solid #e8e8e8;
	border-radius: 8rpx;
	font-size: 28rpx;
	box-sizing: border-box;
	background-color: #fafafa;
	line-height: 1.6;
	
	&:focus {
		border-color: #007aff;
		background-color: #fff;
	}
}

.error-text {
	display: block;
	font-size: 24rpx;
	color: #ff3b30;
	margin-top: 8rpx;
}

.radio-group {
	display: flex;
	gap: 80rpx;
}

.radio-item {
	display: flex;
	align-items: center;
	gap: 12rpx;
	font-size: 28rpx;
}

.radio-text {
	color: #333;
}

.submit-btn {
	width: 100%;
	height: 88rpx;
	background-color: #007aff;
	color: #fff;
	font-size: 32rpx;
	border-radius: 8rpx;
	
	&:disabled {
		background-color: #cccccc;
	}
}

.latest-version-section {
	background-color: #fff;
	padding: 24rpx;
	border-radius: 12rpx;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
}

.section-title {
	display: block;
	font-size: 32rpx;
	font-weight: 600;
	color: #333;
	margin-bottom: 24rpx;
}

.version-card {
	padding: 20rpx;
	border: 2rpx solid #e8e8e8;
	border-radius: 8rpx;
}

.version-info-item {
	display: flex;
	align-items: flex-start;
	margin-bottom: 20rpx;
	
	&.version-desc {
		flex-direction: column;
		align-items: flex-start;
		
		.info-value {
			margin-left: 0;
			margin-top: 12rpx;
		}
	}
}

.info-label {
	font-size: 28rpx;
	font-weight: 600;
	color: #333;
	min-width: 160rpx;
}

.info-value {
	font-size: 28rpx;
	color: #666;
	line-height: 1.6;
	
	&.status-1 {
		color: #00b42a;
	}
	
	&.status-2 {
		color: #ff9500;
	}
}

.empty-data {
	text-align: center;
	padding: 80rpx 0;
}

.empty-text {
	font-size: 28rpx;
	color: #999;
}

.download-btn {
	width: 100%;
	height: 88rpx;
	background-color: #007aff;
	color: #fff;
	font-size: 32rpx;
	border-radius: 8rpx;
	margin-top: 20rpx;
}

/* 版本相同庆祝提示 */
.celebration-box {
	background-color: #f0f8ff;
	padding: 40rpx;
	border-radius: 16rpx;
	margin-top: 32rpx;
	text-align: center;
	box-shadow: 0 4rpx 20rpx rgba(0, 122, 255, 0.1);
	animation: pulse 2s ease-in-out infinite;
}

@keyframes pulse {
	0%, 100% {
		transform: scale(1);
	}
	50% {
		transform: scale(1.05);
	}
}

.celebration-title {
	font-size: 48rpx;
	font-weight: bold;
	color: #007aff;
	margin-bottom: 16rpx;
	display: block;
}

.celebration-message {
	font-size: 28rpx;
	color: #666;
	line-height: 1.6;
}

/* 下载进度弹窗 */
.download-popup {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background-color: rgba(0, 0, 0, 0.5);
	display: flex;
	align-items: center;
	justify-content: center;
	z-index: 9999;
}

.popup-content {
	width: 85%;
	padding: 48rpx 32rpx;
	background-color: #fff;
	border-radius: 16rpx;
	text-align: center;
}

.popup-title {
	display: block;
	font-size: 32rpx;
	font-weight: 600;
	color: #333;
	margin-bottom: 32rpx;
}

.progress-container {
	position: relative;
	width: 100%;
	margin-bottom: 32rpx;
}

.progress-container progress {
	width: 100%;
	height: 8rpx;
}

.progress-text {
	position: absolute;
	top: -40rpx;
	left: 50%;
	transform: translateX(-50%);
	font-size: 32rpx;
	font-weight: 600;
	color: #007aff;
}

.download-error {
	font-size: 28rpx;
	color: #ff3b30;
	margin-bottom: 32rpx;
}

.close-btn {
	width: 100%;
	height: 88rpx;
	background-color: #f5f5f5;
	color: #333;
	font-size: 32rpx;
	border-radius: 8rpx;
}
</style>
